#include "mystdio.h"

my_FILE* my_fopen(const char* path, const char* flag)
{
    int flag1 = 0;
    int iscreat = 0;
    mode_t mode = 0666;
    if (strcmp(flag, "r") == 0)
    {
        flag1 = (O_RDONLY);
    }
    else if (strcmp(flag, "w") == 0)
    {
        flag1 = (O_WRONLY | O_CREAT | O_TRUNC);
        iscreat = 1;
    }
    else if (strcmp(flag, "a") == 0)
    {
        flag1 = (O_WRONLY | O_CREAT | O_APPEND);
        iscreat = 1;
    }
    int fd = 0;
    if (iscreat)
    {
        fd = open(path, flag1, mode);
    }
    else 
    {
        fd = open(path, flag1);
    }
    if (fd < 0)
        return NULL;
    my_FILE* fp = (my_FILE*)malloc(sizeof(my_FILE));
    if (!fp)
        return NULL;

    fp->fileno = fd;
    fp->flags = FFLUSH_LINE;
    fp->cap = LINE_SIZE;
    fp->pos = 0;

    return fp;

}
ssize_t my_fwrite(my_FILE* fp, const char* data, int len)
{
    memcpy(fp->cache + fp->pos, data, len);
    
    fp->pos += len;

    if ((fp->flags&FFLUSH_LINE) && (fp->cache[fp->pos - 1] == '\n'))
    {
        write(fp->fileno, fp->cache, fp->pos);
        fp->pos = 0;
    }
    return len;
}
void my_fflush(my_FILE* fp)
{    
    write(fp->fileno, fp->cache, fp->pos);
    fp->pos = 0;
}
void my_fclose(my_FILE* fp)
{
   my_fflush(fp);
   close(fp->fileno);
   free(fp);
}


